package com.aaa.filter;


import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    Logger logger = Logger.getLogger(LogFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("LoginFilter----init()");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求的url
        String url =  request.getRequestURI();

        //获取session
        HttpSession httpSession = request.getSession();
        Object object = httpSession.getAttribute("login");

        boolean login = false;
        if(object!=null){
            login = (boolean) object;
        }

        if (login||url.contains("login.html")||url.contains("LoginServlet")||url.contains("css")||url.contains("js")||url.contains("img")||url.contains("common")){
            //放行  将拦截方向传递  下一个拦截器
            filterChain.doFilter(request,response);
        }else{
            response.sendRedirect("/login/login.html");
        }
    }

    @Override
    public void destroy() {
        logger.info("LoginFilter----destroy()");
    }
}
